package com.iwithlong.log;

import com.iwithlong.entity.OperateLog;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * User : liulu
 * Date : 17-8-29 下午3:00
 * version $Id: LogInterceptor.java, v 0.1 Exp $
 */
public class LogInterceptor implements HandlerInterceptor {

    private static String[] NO_LOG_URL = {"/css", "/js", "/images", "/assets"};


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        OperateLog operateLog = new OperateLog();

        String requestURI = getUri(request);

        operateLog.setUrl(requestURI);
        operateLog.setClientIp(request.getRemoteAddr());

        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-agent"));
        operateLog.setClientOs(userAgent.getOperatingSystem().getName());
        operateLog.setClientBrowser(userAgent.getBrowser().getName() + ": " + userAgent.getBrowserVersion());

        ThreadLocalStore.setOperateLog(operateLog);

        return true;
    }

    private String getUri(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();
        if (StringUtils.isNoneEmpty(contextPath)) {
            requestURI = StringUtils.substring(requestURI, contextPath.length());
        }
        return requestURI;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        OperateLog operateLog = ThreadLocalStore.getOperateLog();
        if (ThreadLocalStore.getOperateLog() != null && checkUrl(getUri(httpServletRequest))) {

            LogUtil.setSessionOperator(ThreadLocalStore.getOperateLog());

            operateLog.setLogLevel(LogLevel.MINOR.getCode());
            operateLog.setOperatorType(LogOperatorType.OP_WATER.getCode());
            operateLog.setLogContent("操作流水, 请求方法:" + httpServletRequest.getMethod());

            LogUtil.log(operateLog);
        }


    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        ThreadLocalStore.removeOprateLog();
    }

    private boolean checkUrl(String url) {
        for (String s : NO_LOG_URL) {
            if (StringUtils.startsWith(url, s)) {
                return false;
            }
        }
        return true;
    }
}
